package com.hannesdorfmann.mosby3.sample.provider;

import com.hannesdorfmann.mosby3.sample.ResourceTable;
import com.hannesdorfmann.mosby3.sample.slice.MainAbilitySlice;
import ohos.agp.components.*;
import ohos.app.AbilityContext;

/**
 * ListItemProvider
 */
public class ListItemProvider extends BaseItemProvider {
    MainAbilitySlice.Demo[] itemList;
    private AbilityContext context;


    /**
     * Item Provider Constructor
     *
     * @param itemList List of data model
     * @param context  context
     */
    public ListItemProvider(MainAbilitySlice.Demo[] itemList, AbilityContext context) {
        this.itemList = itemList;
        this.context = context;
    }

    @Override
    public int getCount() {
        return itemList.length;
    }

    @Override
    public Object getItem(int index) {
        return itemList[index];
    }

    @Override
    public long getItemId(int index) {
        return index;
    }

    @Override
    public Component getComponent(int index, Component component, ComponentContainer componentContainer) {
        Component itemComponent = component;
        ViewHolder viewHolder;
        if (itemComponent == null) {
            itemComponent = LayoutScatter.getInstance(componentContainer.getContext())
                    .parse(ResourceTable.Layout_item_sample, componentContainer, false);
        }
        MainAbilitySlice.Demo content = (MainAbilitySlice.Demo) getItem(index);
        viewHolder = new ViewHolder(itemComponent);
        viewHolder.item.setText(content.toString());

        // Make divider invisible when current item is the last one
        if (index == getCount() - 1) {
            Image mDivider = (Image) itemComponent.findComponentById(ResourceTable.Id_divider);
            if (mDivider != null) {
                mDivider.setVisibility(Component.INVISIBLE);
            }
        }
        return itemComponent;
    }

    public class ViewHolder{
        public Text item;
        public Image divider;
        public ViewHolder(Component itemComponent) {
            item = (Text) itemComponent.findComponentById(ResourceTable.Id_item_index);
            divider = (Image) itemComponent.findComponentById(ResourceTable.Id_divider);
        }

    }
}
